<template>
  <div class='editTableContainer'>
    <vxe-toolbar>
      <template v-slot:tools>
        <el-button size='small' type="primary" icon="el-icon-edit" @click="addNewRow">新增一行数据</el-button>
        <el-button size='small' type="success" icon="el-icon-edit" @click="copyProductInfo">复制选中数据</el-button>
        <el-button size='small' type="danger" @click="deleteSelectedRow">删除选中行</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table ref='xTable'
               border
               resizable
               keep-source
               auto-resize
               show-overflow
               show-footer
               :footer-method="footerMethod"
               :footer-cell-class-name="footerCellClassName"
               @edit-closed="editClosedEvent"
               @checkbox-all="selectAllEvent"
               @checkbox-change="selectChangeEvent"
               :data="tableData"
               :edit-config="{trigger: 'click', mode: 'cell'}">
      <vxe-table-column v-for="(config, index) in columnConf" :key="index" v-bind="config" >


      </vxe-table-column>
    </vxe-table>
  </div>
</template>

<script>
export default {
  name: 'editTableView',
  props: {
    config: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    columnConf() {
      const tmpColumnConf = [
        {type: 'seq', width: 60, fixed: 'left'},
        {type: 'checkbox', width: 50, fixed: null}
      ]

      Object.keys(this.config).forEach(key => {
        const tmpConf = this.config[key]
        const {type} = tmpConf
        const editRender = {name: 'input', attrs: {type: 'text'}}
        const tmpColumn = {field: key, title: tmpConf.title}
        const editRenderName = this.R.prop('editRenderName', tmpConf)

        if (!this.R.isNil(editRenderName)) {
          editRender.name = editRenderName

          const optionsGet = tmpConf['optionsGet']

          if (optionsGet instanceof Function) {
            editRender.optionsGet = tmpConf['optionsGet']
          }
        }
        if (type === 'select') {
          editRender.name = '$select'
          editRender.options = tmpConf['optionsGet']()
          editRender.props = {clearable: true}
        }
        if (type === 'number') {
          editRender.name = '$input'
          editRender.props = {type: 'number'}
        }
        tmpColumn.editRender = editRender
        tmpColumnConf.push(tmpColumn)
      })
      return tmpColumnConf
    }
  },
  data: () => {
    return {
      tableData: [],
      selectedTableData: []
    }
  },
  mounted() {
    this.addNewRow()
  },
  methods: {
    selectAllEvent({records}) {
      this.selectedTableData = records
    },
    selectChangeEvent({records}) {
      this.selectedTableData = records
    },
    async addNewRow() {
      const record = {}

      Object.keys(this.config).forEach(key => {
        record[key] = this.R.pathOr('', [key, 'default'], this.config)
      })
      const {row: newRow} = await this.$refs.xTable.insert(record)

      await this.$refs.xTable.setEditRow(newRow)
    },
    save() {
      const {insertRecords, removeRecords, updateRecords} = this.$refs.xTable.getRecordset()

      this.tableData.splice(0, 0, ...insertRecords)

      removeRecords.forEach(item => {
        const tmpIndex = this.R.findIndex(this.R.propEq('_XID', item['_XID']), this.tableData)

        if (tmpIndex !== -1) {
          this.tableData.splice(tmpIndex, 1)
        }
      })

      updateRecords.forEach(item => {
        const tmpIndex = this.R.findIndex(this.R.propEq('_XID', item['_XID']), this.tableData)

        if (tmpIndex !== -1) {
          this.tableData.splice(tmpIndex, 1, item)
        }
      })

      this.$refs.xTable.reloadData(this.tableData)
    },
    async copyProductInfo() {
      const selectRecords = this.$refs.xTable.getCheckboxRecords()
      await  this.$refs.xTable.insert(selectRecords)
    },
    deleteSelectedRow() {
      this.$refs.xTable.removeCheckboxRow()
    },
    editClosedEvent({row, column}) {
      const {property} = column

      // if (!this.$refs.xTable.isUpdateByRow(row, property)) {
      //   return
      // }
      const tmpConf = this.config[property]

      if (this.R.isNil(tmpConf)) {
        return
      }
      const cb = tmpConf['valueChangeEvent']

      if (!(cb instanceof Function)) {
        return
      }
      return cb(row)
    },
    meanNum (list, field) {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
      return count / list.length
    },
    sumNum (list, field) {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
      return count
    },
    footerCellClassName ({ $rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        if ($rowIndex === 0) {
          return 'col-blue'
        }
      }
    },
    footerMethod ({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计'
          }
          if (['orderProductNumber'].includes(column.field)) {
            return this.sumNum(data, column.field)
          } else if (['totalPrice'].includes(column.field)) {
            return this.sumNum(data, column.field)
          }
          return null
        }),
      ]
    }
  }
}
</script>

<style scoped>
.editTableContainer {
  width: 100%;
  height: 100%;
}
</style>
